<template>
  <div>
    <a-modal title="关联多渠道配送单" :visible="visible" @before-open="open" @ok.stop="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="800px" :mask-closable="false">
      <div class="title">
        <div :class="['title-item', step == 1 ? 'first' : '']"> 获取亚马逊FBA订单</div>
        <div :class="['title-item', step == 2 ? 'second' : '']"> 确认关联</div>
      </div>
      <div v-if="step == 1">
        <div style="margin: 10px 0; display: flex">
          <div>
            <span>站点：</span>
            <span>{{ $extract(info, 'customOrderInfo.marketplaceId') }}</span>
          </div>
          <div style="margin-left: 50px">
            <span>店铺：</span>
            <span>{{ $extract(info, 'customOrderInfo.shopName') }}</span>
          </div>
        </div>
        <div>
          <span>亚马逊订单号：</span>
          <a-input v-model="orderId" placeholder="例S01-240****-9454***" :style="{ width: '180px' }" />
          <span>
            <a-tooltip content="以S开头的就是亚马逊订单号,即是多渠道配送订单">
              <icon-question-circle-fill style="margin-left: 10px" />
            </a-tooltip>
          </span>
        </div>
      </div>
      <div v-else class="info">
        <div class="item">
          <div class="label">店铺：</div>
          <div class="value">{{ $extract(itemInfo, 'shopName') }}</div>
        </div>
        <div class="item">
          <div class="label">订单状态：</div>
          <div class="value">{{ $extract(itemInfo, 'fulfillmentOrder.fulfillmentOrderStatus') }}</div>
        </div>
        <div class="item">
          <div class="label">订单号：</div>
          <div class="value">{{ $extract(itemInfo, 'platOrderNumber') }}</div>
        </div>
        <div class="item">
          <div class="label">商家订单号：</div>
          <div class="value">{{ $extract(itemInfo, 'fulfillmentOrder.sellerFulfillmentOrderId') }}</div>
        </div>
        <div class="item">
          <div class="label">货件ID：</div>
          <div class="value">{{ $extract(itemInfo, 'fulfillmentShipment.amazonShipmentId') }}</div>
        </div>
        <div class="item">
          <div class="label">包裹编号：</div>
          <div class="value">{{ $extract(itemInfo, 'packageNumber') }}</div>
        </div>
        <div class="item">
          <div class="label">货件状态：</div>
          <div class="value">{{ $extract(itemInfo, 'fulfillmentShipment.fulfillmentShipmentStatus') }}</div>
        </div>
        <div class="item">
          <div class="label">承运商/跟踪号：</div>
          <div class="value">
            <div>{{ filtercarrierCode(itemInfo, 'carrierCode') }}</div>
            <div>{{ filtercarrierCode(itemInfo, 'trackingNumber') }}</div>
          </div>
        </div>
        <div class="item">
          <div class="label">国家：</div>
          <div class="value">{{ $extract(itemInfo, 'fulfillmentOrder.destinationAddress.countryCode') }}</div>
        </div>
        <div class="item">
          <div class="label">省州(邮编)：</div>
          <div class="value">{{ $extract(itemInfo, 'fulfillmentOrder.destinationAddress.stateOrRegion') }}({{ $extract(itemInfo, 'fulfillmentOrder.destinationAddress.postalCode') }})</div>
        </div>
        <div class="item">
          <div class="label">城市：</div>
          <div class="value">{{ $extract(itemInfo, 'fulfillmentOrder.destinationAddress.city') }}</div>
        </div>
        <div class="item">
          <div class="label">收件人/联系电话：</div>
          <div class="value">
            <div>{{ $extract(itemInfo, 'fulfillmentOrder.destinationAddress.name') }}</div>
            <div>{{ $extract(itemInfo, 'fulfillmentOrder.destinationAddress.phone') }}</div>
          </div>
        </div>

        <div class="table-con">
          <div class="title clearfix">
            <div class="left fl">自发货订单商品</div>
            <div class="right fl">亚马逊FBA配送单商品</div>
          </div>
          <div class="body">
            <a-scrollbar style="height: 250px; overflow: auto">
              <div class="body-item clearfix" v-for="item of resultOrderList">
                <div class="left fl">
                  <div v-if="item.pickUpOrderItem.id">
                    <div class="img fl">
                      <a-image :src="item.pickUpOrderItem.productPic" :width="40" :height="40" />
                    </div>
                    <div class="info-box fl ml10">
                      <div>
                        <TextHidden :rowsWidth="200" v-if="item.pickUpOrderItem.sku">{{ item.pickUpOrderItem.sku }}</TextHidden>
                        <div v-else>--</div>
                      </div>
                      <div>
                        <TextHidden :rowsWidth="200" v-if="item.pickUpOrderItem.msku">{{ item.pickUpOrderItem.msku }}</TextHidden>
                        <div v-else>--</div>
                      </div>
                    </div>
                    <div class="num fl"> ×{{ item.pickUpOrderItem.qtyPackageShipped }} </div>
                  </div>
                  <div v-else style="height: 40px; line-height: 40px; margin-left: 20px"> 未匹配上 </div>
                </div>
                <div class="right fl">
                  <div v-if="item.onlinOrderItem.sellerSku">
                    <div class="img fl">
                      <a-image :src="item.onlinOrderItem.productPic" :width="40" :height="40" />
                    </div>
                    <div class="info-box fl ml10">
                      <div>
                        <TextHidden :rowsWidth="200">{{ item.onlinOrderItem.sellerSku }}</TextHidden>
                      </div>
                      <div>
                        <TextHidden :rowsWidth="200">{{ item.onlinOrderItem.asin }}/{{ item.onlinOrderItem.fnsku }}</TextHidden>
                      </div>
                    </div>
                    <div class="num fl"> ×{{ item.onlinOrderItem.quantity }} </div>
                  </div>
                  <div v-else style="height: 40px; line-height: 40px; margin-left: 20px"> 未匹配上 </div>
                </div>
              </div>
            </a-scrollbar>
          </div>
        </div>
      </div>

      <template #footer>
        <div v-if="step == 1">
          <a-button class="gray-outline" @click="handleCancel">取消</a-button>
          <a-button type="primary" style="margin-left: 10px" @click="getAmazonOrder">获取亚马逊订单</a-button>
        </div>
        <div v-else>
          <a-button class="gray-outline" @click="handleCancel">取消</a-button>
          <a-button class="gray-outline ml10" @click="next">上一步</a-button>
          <a-button type="primary" :loading="submitLoading" class="ml10" @click="submit">确认关联</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getFbaMultiChannelOrder, bindFbaMultiChannelOrder } from '@/api/order'
  import _ from 'lodash-es'
  export default defineComponent({
    props: ['info'],
    setup(props: any, { emit }) {
      let visible = ref(false)
      const data: any = reactive({
        step: 1,
        orderId: '',
        itemInfo: {},
        resultOrderList: [],
        submitLoading: false,
      })

      const open = () => {
        console.log(props.info)
      }
      const handleOk = () => {}
      const handleCancel = () => {
        data.step = 1
        visible.value = false
      }

      const next = () => {
        data.step = 1
      }
      const getAmazonOrder = async () => {
        if (!data.orderId) {
          return Message.error('请输入订单号')
        }
        let params = {
          marketplaceId: props.info.marketplaceId,
          platOrderNumber: data.orderId,
          sellerId: props.info.customOrderInfo.sellerId,
          shopName: props.info.customOrderInfo.shopName,
        }
        const res = await getFbaMultiChannelOrder(params)
        data.itemInfo = res?.data || {}
        data.step = 2
        setTableList()
      }

      const setTableList = () => {
        let pickUpOrderList = props.info.packageItemList
        let onlineOrderList = data.itemInfo?.fulfillmentOrderItems || []
        console.log(pickUpOrderList, onlineOrderList)

        let newArr: any = []
        if (pickUpOrderList.length >= onlineOrderList.length) {
          pickUpOrderList.forEach((e: any) => {
            let obj = {
              pickUpOrderItem: e,
              onlinOrderItem: {},
            }
            newArr.push(obj)
          })

          let selNewArr = _.cloneDeep(newArr)

          console.log(selNewArr, onlineOrderList, '2222')

          onlineOrderList.forEach((e: any) => {
            let index: any = selNewArr.findIndex((el: any) => el.pickUpOrderItem.msku == e.sellerSku)
            if (index == -1) {
              let obj = {
                pickUpOrderItem: {},
                onlinOrderItem: e,
              }
              newArr.push(obj)
            } else {
              newArr[index].onlinOrderItem = e
            }
          })
        } else {
          onlineOrderList.forEach((e: any) => {
            let obj = {
              pickUpOrderItem: {},
              onlinOrderItem: e,
            }
            newArr.push(obj)
          })
          let selNewArr = _.cloneDeep(newArr)
          pickUpOrderList.forEach((e: any) => {
            let index: any = selNewArr.findIndex((el: any) => el.onlinOrderItem.sellerSku == e.msku)
            if (index == -1) {
              let obj = {
                pickUpOrderItem: e,
                onlinOrderItem: {},
              }
              newArr.push(obj)
            } else {
              newArr[index].onlinOrderItem = e
            }
          })
        }

        data.resultOrderList = newArr
      }

      const filterStatus = (num: number) => {
        let text = ''
        if (num == 201) {
          text = '已退款'
        } else if (num == -200) {
          text = '已退货'
        } else if (num >= -199 && num <= -100) {
          text = '已取消'
        } else if (num >= 200 && num <= 299) {
          switch (num) {
            case 201:
              text = '待审核'
              break
            case 202:
              text = '待发货'
              break
            case 203:
              text = '部分发货'
              break
            case 204:
              text = '多渠道中'
              break
          }
        } else if (num >= 600 && num <= 699) {
          text = ' 已发货'
        }
        return text
      }

      const getImage = (item: any) => {
        if (item.isCustom) {
          let arr = item.customPics ? item.customPics.split(',') : []
          return arr[0]
        } else {
          return item.productPic
        }
      }

      const submit = async () => {
        try {
          let params = {
            marketplaceId: props.info.marketplaceId,
            orderId: props.info.orderId,
            packageId: props.info.id,
            packageNumber: props.info.packageNumber,
            platOrderNumber: props.info.customOrderInfo.platformOrderNumber,
            sellerFulfillmentOrderId: data.itemInfo?.fulfillmentOrder?.sellerFulfillmentOrderId || '',
            sellerId: props.info.customOrderInfo.sellerId,
            shopName: props.info.customOrderInfo.shopName,
          }
          data.submitLoading = true
          const res: any = await bindFbaMultiChannelOrder(params)
          if (res) {
            Message.success('绑定多渠道订单成功')
            data.step = 1
            data.submitLoading = false
            visible.value = false
            emit('save')
          }
        } catch (error) {
          data.submitLoading = false
        }
      }

      const filtercarrierCode = (info: any, type: string) => {
        let arr = info?.fulfillmentOrderPackageTrackingDetails || []
        if (arr[0]) {
          return arr[0][type]
        } else {
          return '--'
        }
      }

      return {
        ...(toRefs(data) as any),
        visible,
        open,
        handleOk,
        handleCancel,
        next,
        getAmazonOrder,
        filterStatus,
        getImage,
        submit,
        filtercarrierCode,
      }
    },
  })
</script>

<style lang="less" scoped>
  .title {
    width: 100%;
    height: 30px;
    line-height: 30px;
    display: flex;
    background-color: #f6f7f9;
    .title-item {
      width: 50%;
      text-align: center;
      cursor: pointer;
    }

    .first {
      background-color: #3166f5;
      color: white;
      position: relative;
      &::before {
        position: absolute;
        right: -15px;
        top: 0;
        display: inline-block;
        content: '';
        width: 0;
        height: 0;
        border-left: 15px solid #3166f5;
        border-top: 15px solid transparent;
        border-bottom: 15px solid transparent;
      }
    }

    .second {
      background-color: #3166f5;
      color: white;
      position: relative;
      &::before {
        position: absolute;
        left: 0;
        top: 0;
        display: inline-block;
        content: '';
        width: 0;
        height: 0;
        border-left: 15px solid #f6f7f9;
        border-top: 15px solid transparent;
        border-bottom: 15px solid transparent;
      }
    }

    .active {
    }
  }

  .info {
    width: 100%;
    // display: flex;
    // flex-wrap: wrap;
    .item {
      width: 50%;
      margin: 10px 0;
      float: left;
      .label {
        width: 120px;
        text-align: right;
        float: left;
      }
      .value {
        float: left;
        width: calc(100% - 120px);
      }
    }
  }

  .table-con {
    width: 100%;
    .title {
      width: 100%;
      height: 42px;
      border: 1px solid var(--color-neutral-3);
      div {
        width: 50%;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background-color: var(--color-fill-1);
      }
      .left {
        border-right: 1px solid var(--color-neutral-3);
      }
    }
    .body {
      width: 100%;
      .body-item {
        width: 100%;
        height: 50px;
        border: 1px solid var(--color-neutral-3);
        border-top: none;
        .left,
        .right {
          width: 50%;
          height: 100%;
          padding: 5px 10px;
          box-sizing: border-box;
          .num {
            margin-left: 20px;
            font-size: 26px;
            line-height: 40px;
            font-weight: 700;
          }
        }
        .left {
          border-right: 1px solid var(--color-neutral-3);
        }
      }
    }
  }
</style>
